package com.cbgolf.oa.base;

import android.app.Activity;
import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.presenter.IListPresenter;
import com.cbgolf.oa.presenter.IPresenterImp;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.ErrorUtil;
import com.cbgolf.oa.util.Util;

import java.util.List;

/**
 * @author Created by lq on 2017/11/2.
 */

public class BaseModel {

  protected Activity context;
  protected String errorMsg;
  protected int errorCode;
  protected final int INITDATA = 1;
  protected final int REFRESH = INITDATA + 1;
  protected final int LOADMORE = REFRESH + 1;
  protected int page = 0;
  protected int pageSize = 15;

  protected void init(Activity act) {
    this.context = act;
    getInitData();
  }

  protected void getInitData() {

  }

  protected <T> List<T> getList(NetResponse res, Class<T> clazz, int requestType) {
    List<T> list = getList(res, clazz);
    if (Util.listIsNull(list) && requestType == LOADMORE) {
      reducePage();
    }
    return list;
  }

  protected <T> List<T> getList(NetResponse res, Class<T> clazz) {
    try {
      String result;
      try {
        JSONObject json = JSON.parseObject(res.result);
        result = (
            json.containsKey("content") ?
                DataUtil.getJsonString(json, "content")
                : (
                    json.containsKey("status") && json.containsKey("data")
                        && json.containsKey("message") ?
                        json.getString("data") : res.result));
      } catch (Exception e) {
        result = res.result;
      }
      if (Util.isNull(result)) {
        errorMsg = ErrorUtil.NODATA;
        errorCode = ErrorUtil.NODATA_CODE;
        return null;
      }
      List<T> list = JSON.parseArray(result, clazz);
      if (Util.listIsNull(list)) {
        errorMsg = ErrorUtil.NODATA;
        errorCode = ErrorUtil.NODATA_CODE;
      }
      return list;
    } catch (Exception e) {
      Log.e("catch------------", e.toString() + "");
      errorMsg = Util.isNull(res.errorMsg) ? ErrorUtil.NETERROR : res.errorMsg;
      errorCode = ErrorUtil.NETERROR_CODE;
      return null;
    }
  }

  protected <T> T getBean(NetResponse res, Class<T> clazz) {
    return getBean(res.result, clazz);
  }

  protected <T> T getBean(String resul, Class<T> clazz) {
    try {
      String mResult;
      JSONObject json = JSON.parseObject(resul);
      if (json.containsKey(DataManager.KEY_DATA)
          && json.containsKey(DataManager.KEY_STATUS)
          && json.containsKey(DataManager.KEY_MESSAGE)) {
        mResult = json.getString(DataManager.KEY_DATA);
      } else {
        mResult = resul;
      }
      if (Util.isNull(mResult) || null == JSON.parseObject(mResult, clazz)) {
        errorMsg = ErrorUtil.NODATA;
        errorCode = ErrorUtil.NODATA_CODE;
      }
      return JSON.parseObject(mResult, clazz);
    } catch (Exception e) {
      errorMsg = ErrorUtil.NETERROR;
      errorCode = ErrorUtil.NETERROR_CODE;
      return null;
    }
  }

  protected String getJsonString(NetResponse response, String key) {
    try {
      return JSON.parseObject(response.result).getString(key);
    } catch (Exception e) {
      e.printStackTrace();
    }
    return "";
  }

  protected boolean isResOk(NetResponse response) {
    if (200 != response.statusCode) {
      if (!Util.isNetWorkConnected()) {
        errorMsg = ErrorUtil.NONET;
        errorCode = ErrorUtil.NONET_CODE;
      } else {
        errorMsg = response.errorMsg;
        errorCode = ErrorUtil.NETERROR_CODE;
      }
      return false;
    }
    boolean good = DataUtil.isGoodJson(response.result);
    if (!good) {
      errorMsg = ErrorUtil.NETERROR;
      errorCode = ErrorUtil.NETERROR_CODE;
    }
    return good;
  }

  protected boolean isListOk(NetResponse response, Class c) {
    return isResOk(response) && !Util.listIsNull(getList(response, c));
  }

  protected void beanResult(NetResponse response, Class clazz, IPresenterImp worker) {
    if (null == worker) {
      return;
    }
    worker.stopProgress();
    if (!isResOk(response)) {
      worker.getDataFail(errorMsg, errorCode);
      return;
    }

    worker.getDataSuccess(getBean(response, clazz));
  }

  protected void listResult(NetResponse response, Class clazz, int type, IListPresenter worker) {
    if (null == worker) {
      return;
    }
    worker.stopProgress();
    if (!isListOk(response, clazz)) {
      backFail(type, worker);
      return;
    }
    backSuccess(getList(response, clazz), type, worker);
  }

  private void backSuccess(List list, int type, IListPresenter worker) {
    switch (type) {
      case INITDATA:
        worker.getDataSuccess(list);
        break;
      case REFRESH:
        worker.refershSuccess(list);
        break;
      case LOADMORE:
        worker.loadMoreSuccess(list);
        break;
      default:
        break;
    }
  }

  private void backFail(int type, IListPresenter worker) {
    switch (type) {
      case INITDATA:
        worker.getDataFail(errorMsg, errorCode);
        break;
      case REFRESH:
        worker.refershFail(errorMsg, errorCode);
        break;
      case LOADMORE:
        worker.loadMoreFail(errorMsg, errorCode);
        reducePage();
        break;
      default:
        worker.getDataFail(errorMsg, errorCode);
        break;
    }
  }

  private void reducePage() {
    page = ((page > 0) ? --page : 0);
  }


  protected String getErrorMsg(NetResponse response) {
    if (!NetUtils.isNetworkAvailable()) {
      return ErrorUtil.NONET;
    }
    if (null == response) {
      return ErrorUtil.NODATA;
    }
    return Util.isNull(response.errorMsg) ? ErrorUtil.NETERROR : response.errorMsg;
  }
}
